package com.cleaningcloud.erp.service.impl;

import com.cleaningcloud.common.core.exception.ServiceException;
import com.cleaningcloud.common.core.utils.DateUtils;
import com.cleaningcloud.common.core.utils.SecretUtil;
import com.cleaningcloud.common.core.utils.StringUtils;
import com.cleaningcloud.common.security.utils.CommunityTypeConversionUtils;
import com.cleaningcloud.common.security.utils.SecurityUtils;
import com.cleaningcloud.erp.api.domain.ErpCommodity;
import com.cleaningcloud.erp.api.domain.ErpWareCommodityNumber;
import com.cleaningcloud.erp.domain.ErpCommodityUnit;
import com.cleaningcloud.erp.domain.dto.ErpCommodityDto;
import com.cleaningcloud.erp.domain.vo.ErpCommodityVo;
import com.cleaningcloud.erp.mapper.ErpCommodityMapper;
import com.cleaningcloud.erp.mapper.ErpCommodityUnitMapper;
import com.cleaningcloud.erp.mapper.ErpWareCommodityNumberMapper;
import com.cleaningcloud.erp.service.IErpCommodityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 商品管理Service业务层处理
 *
 * @author cleaningcloud
 * @date 2024-09-27
 */
@Service
public class ErpCommodityServiceImpl implements IErpCommodityService {

    private static final Logger log = LoggerFactory.getLogger(ErpCommodityServiceImpl.class);

    @Autowired
    private ErpCommodityMapper erpCommodityMapper;

    @Autowired
    private ErpWareCommodityNumberMapper erpWareCommodityNumberMapper;

    @Autowired
    private ErpCommodityUnitMapper erpCommodityUnitMapper;


    /**
     * 查询商品管理
     *
     * @param commodityId 商品管理主键
     * @return 商品管理
     */
    @Override
    public ErpCommodityVo selectErpCommodityByCommodityId(Long commodityId) {
        ErpCommodityVo commodityVo = erpCommodityMapper.selectErpCommodityByCommodityId(commodityId);
        commodityVo.setCommodityTypeName(CommunityTypeConversionUtils.conversion(commodityVo.getCommodityType()));
        ErpCommodityUnit query = new ErpCommodityUnit();
        query.setCommodityId(commodityVo.getCommodityId());
        commodityVo.setUnitList(erpCommodityUnitMapper.selectErpCommodityUnitList(query));
        return commodityVo;
    }

    /**
     * 查询商品管理列表
     *
     * @param erpCommodity 商品管理
     * @return 商品管理
     */
    @Override
    public List<ErpCommodityVo> selectErpCommodityList(ErpCommodityDto erpCommodity) {
        // isSymbol不为空 则只查询胜博仓
        if (erpCommodity.getParams().get("isSymbol") != null) {
            erpCommodity.getParams().put("wareId", 6);
        }
        //erpCommodity.setCommodityType(CommunityTypeConversionUtils.conversionRegexp(erpCommodity.getCommodityType()));
        if(null != erpCommodity.getCommodityType()){
            erpCommodity.setCommodityType(erpCommodity.getCommodityType().replace('|',','));
        }
        List<ErpCommodityVo> list = erpCommodityMapper.selectErpCommodityList(erpCommodity);
        for (ErpCommodityVo commodityVo : list) {
            commodityVo.setCommodityTypeId(commodityVo.getCommodityType());
            commodityVo.setCommodityType(CommunityTypeConversionUtils.conversion(commodityVo.getCommodityType()));
            // 根据商品id查询库存list
            ErpWareCommodityNumber query = new ErpWareCommodityNumber();
            query.setCommodityId(commodityVo.getCommodityId());
            if (erpCommodity.getParams().get("isSymbol") != null && erpCommodity.getParams().get("isSymbol").toString().equals("1")) {
                query.setWareId(Long.valueOf(erpCommodity.getParams().get("wareId").toString()));
            }
            commodityVo.setNumberList(erpWareCommodityNumberMapper.selectErpWareCommodityNumberList(query));
            ErpCommodityUnit queryUnit = new ErpCommodityUnit();
            queryUnit.setCommodityId(commodityVo.getCommodityId());
            List<ErpCommodityUnit> unitList = erpCommodityUnitMapper.selectErpCommodityUnitList(queryUnit);
            if(!unitList.isEmpty()){
                BigDecimal costPrice = null;
                int i = 1;
                for (ErpCommodityUnit unit : unitList) {
                    if(null != unit.getCostPrice()){
                        costPrice = unit.getCostPrice();
                    }else{
                        if(i == 1){
                            //throw new RuntimeException("该商品最小单位成本价格未设置或改商品单位最小单位未设置在首位！");
                            continue;
                        }
                        unit.setCostPrice(costPrice);
                    }
                    i++;
                }
                commodityVo.setUnitList(unitList);
            }

            //获取商品销售单价,最近一次客户销售价
            ErpCommodityVo obj = new ErpCommodityVo();
            obj.setCommodityId(commodityVo.getCommodityId());
            obj.setCommodityUnitId(commodityVo.getCommodityUnitId());
            ErpCommodityVo saleObj = erpCommodityMapper.getCommoditySalePrice(obj);
            commodityVo.setSalePrice(saleObj == null ? new BigDecimal(0) : saleObj.getSalePrice());
        }
        return list;
    }

    /**
     * 新增商品管理
     *
     * @param erpCommodity 商品管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertErpCommodity(ErpCommodityDto erpCommodity) {
        int check = erpCommodityMapper.checkNoUnique(erpCommodity.getCommodityNo());
        if (check > 0) {
            throw new RuntimeException("商品编号`" + erpCommodity.getCommodityNo() + "`已存在！");
        }
        erpCommodity.setCreateTime(DateUtils.getNowDate());
        erpCommodity.setCreateId(SecurityUtils.getUserId());
        erpCommodity.setCreateName(SecurityUtils.getUsername());
        erpCommodity.setFlag("Y");
        if (StringUtils.isNotEmpty(erpCommodity.getCommodityImgtext())) {
            erpCommodity.setCommodityImgtext(SecretUtil.desEncrypt(erpCommodity.getCommodityImgtext(), SecretUtil.KEY, SecretUtil.IV));
        }
        erpCommodityMapper.insertErpCommodity(erpCommodity);
        // 新增商品单位
        extracted(erpCommodity);
        return 1;
    }

    /**
     * 修改商品管理
     *
     * @param erpCommodity 商品管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateErpCommodity(ErpCommodityDto erpCommodity) {
        // 修改商品单位  先删除原有的商品单位信息  再进行插入
        erpCommodityUnitMapper.deleteErpCommodityUnitByCommodityId(erpCommodity.getCommodityId());
        if (StringUtils.isNotEmpty(erpCommodity.getCommodityImgtext())) {
            erpCommodity.setCommodityImgtext(SecretUtil.desEncrypt(erpCommodity.getCommodityImgtext(), SecretUtil.KEY, SecretUtil.IV));
        }
        extracted(erpCommodity);
        return erpCommodityMapper.updateErpCommodity(erpCommodity);
    }

    private void extracted(ErpCommodityDto erpCommodity) {
        if (erpCommodity.getUnitList() != null && !erpCommodity.getUnitList().isEmpty()) {
            for (ErpCommodityUnit erpCommodityUnit : erpCommodity.getUnitList()) {
                erpCommodityUnit.setCommodityUnitId(erpCommodity.getCommodityId());
                erpCommodityUnit.setCommodityId(erpCommodity.getCommodityId());
                erpCommodityUnit.setUnitRelationship("1" + erpCommodityUnit.getUnitName1() + "=" + erpCommodityUnit.getUnitResult() + erpCommodityUnit.getUnitName2());
            }
            erpCommodityUnitMapper.batchInsert(erpCommodity.getUnitList());
        }
        // 修改商品表商品单位id 默认取第一条
        ErpCommodityUnit query = new ErpCommodityUnit();
        query.setCommodityId(erpCommodity.getCommodityId());
        List<ErpCommodityUnit> erpCommodityUnitList = erpCommodityUnitMapper.selectErpCommodityUnitList(query);
        if (erpCommodityUnitList != null && !erpCommodityUnitList.isEmpty()) {
            erpCommodity.setCommodityUnitId(erpCommodityUnitList.get(0).getCommodityUnitId());
            erpCommodityMapper.updateErpCommodity(erpCommodity);
        }
    }

    /**
     * 批量删除商品管理
     *
     * @param commodityIds 需要删除的商品管理主键
     * @return 结果
     */
    @Override
    public int deleteErpCommodityByCommodityIds(Long[] commodityIds) {
        return erpCommodityMapper.deleteErpCommodityByCommodityIds(commodityIds);
    }

    /**
     * 删除商品管理信息
     *
     * @param commodityId 商品管理主键
     * @return 结果
     */
    @Override
    public int deleteErpCommodityByCommodityId(Long commodityId) {
        return erpCommodityMapper.deleteErpCommodityByCommodityId(commodityId);
    }

    @Override
    @Transactional
    public String importErpCommodity(List<ErpCommodityVo> commodityList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(commodityList) || commodityList.size() == 0) {
            throw new ServiceException("导入商品数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ErpCommodityVo erpCommodityVo : commodityList) {
            try {
                // 验证是否存在这个商品
                Long commodityId = erpCommodityMapper.selectCommodityByNo(erpCommodityVo.getCommodityNo());
                ErpCommodity erpCommodity = new ErpCommodity();
                BeanUtils.copyProperties(erpCommodityVo, erpCommodity);
                if (StringUtils.isNull(commodityId)) {
                    erpCommodity.setCreateTime(DateUtils.getNowDate());
                    erpCommodity.setCreateId(SecurityUtils.getUserId());
                    erpCommodity.setCreateName(SecurityUtils.getUsername());
                    erpCommodity.setFlag("Y");
                    erpCommodity.setCommodityStatus(1L);
                    erpCommodity.setCommodityType(erpCommodity.getCommodityTypeId());
                    erpCommodityMapper.insertErpCommodity(erpCommodity);
                    // 添加商品单位
                    ErpCommodityUnit erpCommodityUnit = new ErpCommodityUnit();
                    erpCommodityUnit.setUnitName1(erpCommodityVo.getUnitName1());
                    if (StringUtils.isNotEmpty(erpCommodityVo.getUnitName2())) {
                        erpCommodityUnit.setUnitName2(erpCommodityVo.getUnitName2());
                    } else {
                        if (StringUtils.isNotEmpty(erpCommodityVo.getUnitName1())) {
                            erpCommodityUnit.setUnitName2(erpCommodityVo.getUnitName1());
                        }
                    }
                    erpCommodityUnit.setUnitResult(erpCommodityVo.getUnitResult() == null ? 1 : erpCommodityVo.getUnitResult());
                    if (StringUtils.isEmpty(erpCommodityVo.getUnitRelationship())) {
                        erpCommodityUnit.setUnitRelationship("1" + erpCommodityVo.getUnitName1() + "=" + erpCommodityVo.getUnitResult() + erpCommodityVo.getUnitName2());
                    } else {
                        erpCommodityUnit.setUnitRelationship(erpCommodityVo.getUnitRelationship());
                    }
                    erpCommodityUnit.setCostPrice(erpCommodityVo.getCostPrice());//成本价
                    erpCommodityUnit.setSymbolPrice(erpCommodityVo.getSymbolPrice());//胜博价
                    erpCommodityUnit.setRetailPrice(erpCommodityVo.getRetailPrice());//零售价
                    erpCommodityUnit.setDistriPrice(erpCommodityVo.getDistriPrice());//经销价
                    erpCommodityUnit.setAgencyPrice(erpCommodityVo.getAgencyPrice());//代理价
                    erpCommodityUnit.setCommodityId(erpCommodity.getCommodityId());
                    erpCommodityUnitMapper.insertErpCommodityUnit(erpCommodityUnit);
                    erpCommodity.setCommodityUnitId(erpCommodityUnit.getCommodityUnitId());
                    erpCommodityMapper.updateErpCommodity(erpCommodity);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、商品编号 " + erpCommodity.getCommodityNo() + " 导入成功");
                } else if (isUpdateSupport) {
                    erpCommodity.setCommodityId(commodityId);
                    erpCommodity.setUpdateBy(operName);
                    // 修改商品单位信息
                    ErpCommodityVo commodityVo = erpCommodityMapper.selectErpCommodityByCommodityId(commodityId);
                    ErpCommodityUnit erpCommodityUnit = new ErpCommodityUnit();
                    erpCommodityUnit.setCommodityUnitId(commodityVo.getCommodityUnitId());
                    erpCommodityUnit.setUnitName1(erpCommodityVo.getUnitName1());
                    if (StringUtils.isNotEmpty(erpCommodityVo.getUnitName2())) {
                        erpCommodityUnit.setUnitName2(erpCommodityVo.getUnitName2());
                    } else {
                        if (StringUtils.isNotEmpty(erpCommodityVo.getUnitName1())) {
                            erpCommodityUnit.setUnitName2(erpCommodityVo.getUnitName1());
                        }
                    }
                    erpCommodityUnit.setUnitResult(erpCommodityVo.getUnitResult() == null ? 1 : erpCommodityVo.getUnitResult());
                    erpCommodityUnit.setCostPrice(erpCommodityVo.getCostPrice());
                    erpCommodityUnit.setRetailPrice(erpCommodityVo.getRetailPrice());
                    if (StringUtils.isEmpty(erpCommodityVo.getUnitRelationship())) {
                        erpCommodityUnit.setUnitRelationship("1" + erpCommodityVo.getUnitName1() + "=" + erpCommodityVo.getUnitResult() + erpCommodityVo.getUnitName2());
                    } else {
                        erpCommodityUnit.setUnitRelationship(erpCommodityVo.getUnitRelationship());
                    }
                    erpCommodityUnit.setCostPrice(erpCommodityVo.getCostPrice());
                    erpCommodityUnit.setRetailPrice(erpCommodityVo.getRetailPrice());
                    erpCommodityUnitMapper.updateErpCommodityUnit(erpCommodityUnit);
                    erpCommodityMapper.updateErpCommodity(erpCommodity);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、商品编号 " + erpCommodity.getCommodityNo() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、商品编号 " + erpCommodity.getCommodityNo() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、商品编号 " + erpCommodityVo.getCommodityNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * @Author Shaw
     * @Description 供三才环科商城（小程序）展示
     * @date: 2025-04-02 14:31
     * @param: //TODO
     */
    @Override
    public List<ErpCommodityVo> selectMallCommodityList(ErpCommodity erpCommodity){
        return erpCommodityMapper.selectMallCommodityList(erpCommodity);
    }
}
